package webstart;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import util.RegistryUtil;
import util.TiffOutput;

import chrriis.dj.nativeswing.NSOption;
import chrriis.dj.nativeswing.swtimpl.NativeComponent;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserEvent;

/**
 * 根据url将网页生成图片
 * 依赖的jar包：
 * 		DJNativeSwing.jar
 * 		DJNativeSwing-SWT.jar
 * 		swt-3.6M3-win32-win32-x86.jar
 *
 */
public class WebPageToImage extends JPanel {
	private static final long serialVersionUID = 1L;

	// 行分隔符
	final static public String LS = System.getProperty("line.separator", "\n");

	// 文件分割符
	final static public String FS = System.getProperty("file.separator", "\\");

	// 以javascript脚本获得网页全屏后大小
	final static StringBuffer jsDimension;

	static {
		jsDimension = new StringBuffer();
		jsDimension.append("var width = 0;").append(LS);
		jsDimension.append("var height = 0;").append(LS);
		jsDimension.append("if(document.documentElement) {").append(LS);
		jsDimension
				.append("  width = Math.max(width, document.documentElement.scrollWidth);")
				.append(LS);
		jsDimension
				.append("  height = Math.max(height, document.documentElement.scrollHeight);")
				.append(LS);
		jsDimension.append("}").append(LS);
		jsDimension.append("if(self.innerWidth) {").append(LS);
		jsDimension.append("  width = Math.max(width, self.innerWidth);")
				.append(LS);
		jsDimension.append("  height = Math.max(height, self.innerHeight);")
				.append(LS);
		jsDimension.append("}").append(LS);
		jsDimension.append("if(document.body.scrollWidth) {").append(LS);
		jsDimension.append(
				"  width = Math.max(width, document.body.scrollWidth);")
				.append(LS);
		jsDimension.append(
				"  height = Math.max(height, document.body.scrollHeight);")
				.append(LS);
		jsDimension.append("}").append(LS);
		jsDimension.append("return width + ':' + height;");
		//System.out.println(jsDimension);
	}
	
	//下载浏览器相关包:
	//http://jarfiles.pandaidea.com/xulrunner.html
	//加载浏览器本地引擎
	static {
		System.setProperty("org.eclipse.swt.browser.XULRunnerPath","C:/xulrunner");//firefox
	}

	public WebPageToImage() {
		
	}

	//DJNative Swing 之JWebBrowser总结  
	//http://www.verydemo.com/demo_c173_i1471.html
	//版本：DJNativeSwing-SWT-1-0-1
	public WebPageToImage(String browserType, final String url, final String fileName, final int dpi, final int maxWidth, final int maxHeight, final String httpUrl, final String caseId) {
		super(new BorderLayout());
		
		//JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
		//add(topPanel, BorderLayout.NORTH);
		
		JPanel webBrowserPanel = new JPanel(new BorderLayout());
		
		NSOption[] nsOption = new NSOption[1];
		if("XULRunner".equals(browserType)) {
			nsOption[0] = JWebBrowser.useXULRunnerRuntime();
		} else if("Webkit".equals(browserType)) {
			nsOption[0] = JWebBrowser.useWebkitRuntime();
		} else {//IE
			nsOption = null;
		}
		final JWebBrowser webBrowser = new JWebBrowser(nsOption);
		//final JWebBrowser webBrowser = new JWebBrowser(null); //默认IE
		//final JWebBrowser webBrowser = new JWebBrowser(JWebBrowser.useXULRunnerRuntime());//mozilla firefox
		//final JWebBrowser webBrowser = new JWebBrowser(JWebBrowser.useWebkitRuntime());//google chrome
		webBrowser.setBarsVisible(false);//地址栏
		webBrowser.setButtonBarVisible(false);//按钮栏
	    webBrowser.setMenuBarVisible(false);//菜单栏
	    webBrowser.setStatusBarVisible(false);//状态栏
		webBrowser.navigate(url);
		
		webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
		add(webBrowserPanel, BorderLayout.CENTER);
		
//		try {
//			Thread.sleep(1000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		} 
		
		webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
			
			// 监听加载进度
			public void loadingProgressChanged(WebBrowserEvent e) {
				// 当加载完毕时
				if (e.getWebBrowser().getLoadingProgress() == 100) {
					String result = (String) webBrowser
							.executeJavascriptWithResult(jsDimension.toString());
					//System.out.println("result = " + result);
					int index = result == null ? -1 : result.indexOf(":");
					NativeComponent nativeComponent = webBrowser
							.getNativeComponent();
					Dimension originalSize = nativeComponent.getSize();
					Dimension imageSize = new Dimension(Integer.parseInt(result
							.substring(0, index)), Integer.parseInt(result
							.substring(index + 1)));
					imageSize.width = Math.max(originalSize.width,
							imageSize.width + 50);
					imageSize.height = Math.max(originalSize.height,
							imageSize.height + 50);
					nativeComponent.setSize(imageSize);
					BufferedImage image = new BufferedImage(imageSize.width,
							imageSize.height, BufferedImage.TYPE_INT_RGB);
					nativeComponent.paintComponent(image);
					nativeComponent.setSize(originalSize);
					// 当网页超出目标大小时
					if (imageSize.width > maxWidth
							|| imageSize.height > maxHeight) {
						// 截图部分图形
						// image = image.getSubimage(0, 0, maxWidth, maxHeight);

						//此部分为使用缩略图 
//						int width = image.getWidth(), height = image.getHeight();
//						AffineTransform tx = new AffineTransform();
//						tx.scale((double) maxWidth / width, (double) maxHeight / height);
//						AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
//						image = op.filter(image, null);
					}
					try {
						// 输出图像
						if(fileName == null || "".equals(fileName) || "&nbsp;".equals(fileName)) {
							String filePath = TiffOutput.upload(image, dpi);
							
							//更新广告案例的图片路径
							if(caseId != null && !"".equals(caseId) && !"&nbsp;".equals(caseId)) {
								Map<String, String> paraMap = new HashMap<String, String>();
								paraMap.put("caseId", caseId);
								paraMap.put("imagePath", filePath);
								String retObj = (String)DataViewUtil.parseObject(httpUrl, paraMap);
								System.out.println("返回：" + retObj);
							}
						} else {
							TiffOutput.getTiffFile(image, fileName, dpi);
						}
						//ImageIO.write(image, "bmp", new File(fileName));
					} catch (Exception ex) {
						ex.printStackTrace();
						
						// 退出操作
						System.exit(0);
					}
					// 退出操作
					System.exit(0);
				}
			}
		}

		);
		
		JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));
		add(bottomPanel, BorderLayout.SOUTH);

	}

	public static void main(String[] args) throws InterruptedException, InvocationTargetException, UnsupportedEncodingException {
		System.out.println("开始生成图片");

		if(args.length <4) {
			System.out.println("请先配置好4个参数：url、outputFile、dpi、browserType");
			/*
			//测试
			args = new String[7];
			args[0] = "www.baidu.com";
			args[1] = "I:/test.tif"; //I:/test.tif
			args[2] = "300";
			args[3] = "Webkit"; //Webkit or XULRunner or IE
			args[4] = "http://localhost:8080";
			args[5] = "";//caseId  //402880e43ff25cd0013ff272685b001c
			args[6] = "G:/Program Files/Safari/Apple Application Support";
			*/
			return;
		}
		RegistryUtil.registryApple(args[6]);
		
		//String urlArg = args[0].trim();
		//final String url = java.net.URLDecoder.decode(urlArg,"UTF-8");
		final String url = args[0].trim();
		final String outputFile = args[1].trim();
		String dpiStr = args[2].trim();
		final int dpi = Integer.parseInt(dpiStr);
		final String browserType = args[3].trim();
		
		System.out.println("网址：  " + url);
		System.out.println("输出图片： " + outputFile);
		System.out.println("分辨率：" + dpi);
		System.out.println("浏览器类型： " + browserType);
		
		final String httpUrl = args[4]+"/services?action=webstart.JnlpAction&operate=saveImagePath";
		final String caseId = args[5];
		
		NativeInterface.open();
		//SwingUtilities.invokeAndWait(new Runnable() {  //在 AWT 事件指派线程上同步执行
		SwingUtilities.invokeLater(new Runnable() { // 在 AWT 事件指派线程上异步执行
			public void run() {
				// SWT组件转Swing组件，不初始化父窗体将无法启动webBrowser
				JFrame frame = new JFrame("以DJ组件保存指定网页截图");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				
				// 加载网页，最大保存为640x480的截图
				frame.getContentPane().add(new WebPageToImage(browserType, url, outputFile, dpi,2000, 800, httpUrl, caseId), BorderLayout.CENTER);
				//全屏
				frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
				//frame.setSize(800, 600);
				// 仅初始化，但不显示
				frame.invalidate();
				frame.pack();
				//frame.setVisible(true);
				//frame.setLocationByPlatform(true); 
				//frame.dispose();
			}
		});
		NativeInterface.runEventPump();
		NativeInterface.close();
	}
	

}
